package com.jyh.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jyh.order.bean.Order;
import com.jyh.order.properties.OrderProperties;
import com.jyh.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
//@RefreshScope//自动刷新 激活配置中心的自动刷新功能
public class OrderController {

    private final OrderService orderService;
    private final OrderProperties orderProperties;

//    @Value("${order.timeout}")
//    String orderTimeout;
//
//    @Value("${order.timeout}")
//    String orderAutoConfirm;


    @GetMapping("/config")
    public String getConfig() {
        return "order.timeout:" + orderProperties.getTimeout() +
                ",order.autoConfirm:" + orderProperties.getAutoConfirm() +
                ",order.db-url=" + orderProperties.getDbUrl();
    }

    // 创建订单
    @GetMapping("/create")
    public Order createOrder(@RequestParam("productId") Long productId,
                             @RequestParam("userId") Long userId) {
        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", blockHandler = "seckillFallback")
    public Order seckill(@RequestParam(value = "productId",defaultValue = "1000") Long productId,
                             @RequestParam(value = "userId",required = false) Long userId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    private Order seckillFallback(Long productId, Long userId, BlockException e) {
        System.out.println("seckillFallback...");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息：" + e.getClass());
        return order;
    }

    /**
     * 模拟读/写数据库，操作同一个资源。实现当写数据库流量大时，才限制读数据库流量；写数据库流量小时，读数据库流量无限制（优先写）
     */
    @GetMapping("/writeDb")
    public String writeDb() {
        System.out.println("writeDb...");
        return "writeDb success....";
    }

    @GetMapping("/readDb")
    public String readDb() {
        System.out.println("readDb...");
        return "readDb success....";
    }
}